<template>
  <a-tree-select
    v-model="currentValue"
    v-bind="$attrs"
    v-on="$listeners"
    dropdownMatchSelectWidth
    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
    :replaceFields="replaceFields"
    placeholder="请选择"
    :tree-data="treeData"
    allow-clear
    :getPopupContainer="getPopupContainer"
  >
    <a-icon v-if="loading" style="color: #096dd9" slot="suffixIcon" type="loading" />
    <a-spin v-if="loading" slot="notFoundContent" size="small" />
  </a-tree-select>
</template>
<script>
/*
*
* 下拉公用树组件
*
*   {
          name: '检查区域', valueKey: 'respAreaId', type: SelectTreeCommon,
          params: { sources: 0 },
          linkParamsKey: 'id',
          api: e => Api.subPackArea({}, e)
        },

*   {
          name: '隐患类型', valueKey: 'treeLabelId', type: SelectTreeCommon,
          needLink: false,
          api: async () => {
            let res = await request2({ url: 'cscec-pms-app-business-ycq/safety/getLabelTypesLeft/HIDDEN_DANGERS_LEFT' })
            if (res.code === this.SUCCESS_CODE) {
              return { code: this.SUCCESS_CODE, data: [res.data] }
            }
            return { code: this.SUCCESS_CODE, data: [] }
          }
        },


        * //不包含西南公司、不包含部门的下拉树
        * 也就是所有分公司，所有项目部，没有三级权限
         {
              type: SelectTreeCommon,
              value: 'penaltyOrgId',
              label: '被处罚单位',
              attrs: {
                replaceFields: { children: 'children', title: 'label', key: 'id', value: 'id' },
                needLink: false,
                api: async () => {
                  let res = await getCustOrgTree({
                    containTags: ['CO', 'BC', 'PD'],
                    containVirtual: 0,
                    resultWithCODept: false,
                    resultWithBCDept: false,
                    resultWithPDDept: false
                  })
                  if (res.status === 200 && res.data instanceof Array) {
                    return { code: this.SUCCESS_CODE, data: res.data[0].children }
                  }
                }
              }
            },
            *
            *
            * 三级权限分公司，项目（不是项目部，这个是带projectId）
            *  {
              type: SelectTreeCommon,
              value: 'penaltyOrgId',
              label: '被处罚单位',
              show: this.form.penaltyType === 0,
              attrs: {
                returnFindItem: true,
                replaceFields: { children: 'childTree', title: 'orgName', key: 'orgId', value: 'orgId' },
                needLink: false,
                api: async () => {
                  let res = await queryProjectTree()
                  if (res.code === 200 && res.data) {
                    return { code: this.SUCCESS_CODE, data: res.data.childTree }
                  }
                  return { code: this.SUCCESS_CODE, data: [] }
                }
              },
              on: {
                selectChange: e => {
                  this.form.penaltyOrgName = e.label
                  this.form.penaltyOrgTag = e.data.tag[1]
                }
              }
            },
* */
import { hasLetter } from '@/utils/regExpression'

export default {
  name: 'SelectTreeCommon',
  components: {},
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object, Number]
    },
    form: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 需要联动的表单名
    keyValue: {
      type: String,
      default: () => 'projectId'
    },
    needLink: {
      type: Boolean,
      default: true
    },
    api: {
      type: [Function, Object],
      default() {
        return {}
      }
    },
    params: {
      type: Object,
      default() {
        return {}
      }
    },
    //外部参数需要用到关联key的key
    linkParamsKey: {
      type: String,
      default: () => 'id'
    },
    replaceFields: {
      type: Object,
      default() {
        return { children: 'children', title: 'name', key: 'id', value: 'id' }
      }
    },
    //如果是编辑，第一次不要重置绑定的值。。。。
    isEdit: {
      type: Boolean,
      default: () => false
    },
    //是否寻找选中的条目，默认不返回，因为递归
    returnFindItem: {
      type: Boolean,
      default: () => false
    },
    // 是否禁用父级，只启用末级
    parentDisabled: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      treeData: [],
      loading: false,
      isCanClear: null // 用来标记是否能清除，因为编辑时，第一次不能清除
    }
  },
  computed: {
    // 需要联动的表单值
    attr() {
      let attrValue
      const keys = this.keyValue.split('.')
      const findValueFromKeys = (data, key) => {
        if(data instanceof Object && keys.some(k => k === key)){
          return findValueFromKeys(data[key], keys[keys.findIndex(k => k === key) + 1])
        }
        return data
      }
      if(keys && !!keys.length){
        attrValue = findValueFromKeys(this.form, keys[0])
      }
      return attrValue
    },
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function() {
        return this.value || void 0
      },
      set: function(value) {
        this.$emit('input', value)
        this.$emit('change', value)
        if (this.returnFindItem) {
          let res = this.findItem(this.treeData, value)
          if (res) {
            this.$emit('selectChange', res)
            // 新增一个 如果选择的项目部返回父级节点数据
            if(res.parentId&&res.tageCode === 'PD') {
              let res3 = this.findItem(this.treeData, res.parentId, null)
              if (res3) {
                this.$emit('getParentNode', res3)
              }
            }
          }
          // 这里不确定是否其他地方使用 所以没改
          let res2 = this.findItem(this.treeData, value, null)
          if (res2) {
            this.$emit('selectParentChange', res2)
          }
        }
      }
    }
  },
  watch: {
    isEdit: {
      handler(val) {
        this.isCanClear = !val
      },
      immediate: true
    },
    attr(val) {
      if (!this.needLink) return

      // 在搜索组件(SearchData)中重置自身的值
      if (!this.isEdit) {
        this.currentValue = void 0
        this.$emit('resetSelf')
      }
      // 表单中，编辑的时候，第一次不清空值，后面要清空值
      if (this.isEdit && this.isCanClear) {
        this.currentValue = void 0
      } else {
        this.isCanClear = true
      }
      
      this.treeData = []
      val && this.getData()
    },
    needLink: {
      immediate: true,
      handler(val) {
        if (!val) {
          this.getData()
        }
      }
    }
  },
  methods: {
    /**
     * @description: 扁平化数据
     * @param {array} data
     * @return {void}
     */
    flatTree(tree) {
        for (let i = 0; i < tree.length; i++) {
            const node = tree[i]
            let name = node.projectName ? node.projectName : node.orgName
            node.orgName = name
            if (node[this.replaceFields.children]) {
              if(this.parentDisabled) {// 禁用父级，只启用末级
                // 禁用父级节点
                node.disabled = true
              }
              this.flatTree(node[this.replaceFields.children])
            }
        }
    },
    findItem(list, id) {
      let res
      for (let i = 0; i < list.length; i++) {
        let v = list[i]
        if (v[this.replaceFields.value] === id) {
          res = v
          break
        } else {
          if (v[this.replaceFields.children] && v[this.replaceFields.children].length) {
            res = this.findItem(v[[this.replaceFields.children]], id)
            if (res) break
          }
        }
      }
      return res
    },
    findParentItem(list, id, parent) {
      let res
      for (let i = 0; i < list.length; i++) {
        let v = list[i]
        if (v[this.replaceFields.children] && v[this.replaceFields.children].length) {
          res = this.findParentItem(v[[this.replaceFields.children]], id, v)
          if (res) break
        } else {
          if (v[this.replaceFields.value] === id) {
            res = parent
            break
          }
        }
      }
      return res
    },
    getPopupContainer() {
      return document.querySelector('body')
    },
    async getData() {
      if (this.attr && hasLetter.test(this.attr)) return // 包含字母的id不是项目，需排除
      this.loading = true
      if (this.needLink) {
        this.params[this.linkParamsKey] = this.attr
      }
      let res = await this.api(this.params)
      this.loading = false
      if (res.code === this.SUCCESS_CODE) {
        this.flatTree(res.data)
        this.treeData = res.data
        console.log('111', this.treeData);
      }
    }
  }
}
</script>
